package com.hs.srm.admin.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;



/**
 * 文件处理工具类
 * @author yanfei
 *
 * @date 2019年3月1日
 */
public class FileUtils {

	public static File getFile(File directory, String... names) {
        if (directory == null) {
            throw new NullPointerException( "directorydirectory must not be null");
        }
        if (names == null) {
            throw new NullPointerException("names must not be null");
        }
        File file = directory;
        for (String name : names) {
            file = new File(file, name); //根据一个父File对象和一个子文件/目录得到File对象
        }
        // File(String parent, String child):根据一个目录和一个子文件/目录得到File对象
        return file;
    }
	
	 public static File getFile(String... names) {
	        if (names == null) {
	            throw new NullPointerException("names must not be null");
	        }
	        File file = null;
	        for (String name : names) {
	            if (file == null) {
	                file = new File(name);
	            }
	            else {
	                file = new File(file, name);
	            }
	        }
	        return file;
	 }
	 
	 public static void cleanDirectory(File directory) throws IOException {
	        if (!directory.exists()) {
	            String message = directory + " does not exist";
	            throw new IllegalArgumentException(message);
	        }

	        if (!directory.isDirectory()) {
	            String message = directory + " is not a directory";
	            throw new IllegalArgumentException(message);
	        }

	        File[] files = directory.listFiles();
	        if (files == null) { // null if security restricted
	            throw new IOException("Failed to list contents of " + directory);
	        }

	        IOException exception = null;
	        for (File file : files) {
	            try { forceDelete(file);}
	            catch (IOException ioe) {
	                exception = ioe;
	            }
	        }

	        if (null != exception) {
	            throw exception;
	        }
	 }
	 
	  public static void deleteDirectory(File directory) throws IOException {
	        if (!directory.exists()) {
	            return;
	        }

	        cleanDirectory(directory);

	        if (!directory.delete()) {
	            String message = "Unable to delete directory " + directory + ".";
	            throw new IOException(message);
	        }
	    }
	 public static void forceDelete(File file) throws IOException {
	        if (file.isDirectory()) {
	            deleteDirectory(file);
	        }
	        else {
	            boolean filePresent = file.exists();
	            if (!file.delete()) {
	                if (!filePresent) {
	                    throw new FileNotFoundException("File does not exist: " + file);
	                }
	                String message = "Unable to delete file: " + file;
	                throw new IOException(message);
	            }
	        }
	    }
	  public static boolean deleteQuietly(File file) {
	        if (file == null) {
	            return false;
	        }
	        try {
	            if (file.isDirectory()) {
	                cleanDirectory(file);
	            }
	        }
	        catch (Exception ignored) {
	        }

	        try {
	            return file.delete();
	        }
	        catch (Exception ignored) {
	            return false;
	        }
	    }
	  public static void forceMkdir(File directory) throws IOException {
	        if (directory.exists()) {
	            if (!directory.isDirectory()) {
	                String message = "File " + directory + " exists and is "
	               + "not a directory. Unable to create directory.";
	                throw new IOException(message);
	            }
	        }
	        else {
	            if (!directory.mkdirs()) {
	                // Double-check that some other thread or process hasn't made
	                // the directory in the background
	                if (!directory.isDirectory()) {
	                    String message = "Unable to create directory " + directory;
	                    throw new IOException(message);
	                }
	            }
	        }
	  }
	  public static long sizeOf(File file) {

	        if (!file.exists()) {
	            String message = file + " does not exist";
	            throw new IllegalArgumentException(message);
	        }

	        if (file.isDirectory()) {
	            return sizeOfDirectory(file);
	        }
	        else {
	            return file.length();
	        }

	    }
	  public static long sizeOfDirectory(File directory) {
	        checkDirectory(directory);

	        final File[] files = directory.listFiles();
	        if (files == null) { // null if security restricted
	            return 0L;
	        }
	        long size = 0;

	        for (final File file : files) {

	            size += sizeOf(file);
	            if (size < 0) {
	                break;

	            }

	        }

	        return size;
	    }
	   private static void checkDirectory(File directory) {
	        if (!directory.exists()) {
	            throw new IllegalArgumentException(directory + " does not exist");
	        }
	        if (!directory.isDirectory()) {
	            throw new IllegalArgumentException(directory
	                    + " is not a directory");
	        }
	    }
	   //创建Excel
	   public static void createFile(HttpServletResponse response, HSSFWorkbook workbook) {
			// 设置文件名
		    String fileName ="用户信息";
		    try {
		    	// 捕获内存缓冲区的数据，转换成字节数组
		    	ByteArrayOutputStream out = new ByteArrayOutputStream();
		    	workbook.write(out);
		    	// 获取内存缓冲中的数据
		    	byte[] content = out.toByteArray();
		    	// 将字节数组转化为输入流
		    	InputStream in = new ByteArrayInputStream(content);
		    	//通过调用reset（）方法可以重新定位。         	
		    	response.reset();
		        // 如果文件名是英文名不需要加编码格式，如果是中文名需要添加"iso-8859-1"防止乱码
		        response.setHeader("Content-Disposition", "attachment; filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		        response.addHeader("Content-Length", "" + content.length);
		        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		        ServletOutputStream outputStream = response.getOutputStream();
		        BufferedInputStream bis = new BufferedInputStream(in);
		        BufferedOutputStream bos = new BufferedOutputStream(outputStream);
		        byte[] buff = new byte[8192];
		        int bytesRead;
		        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
		            bos.write(buff, 0, bytesRead);
		        }
		        bis.close();
		        bos.close();
		        outputStream.flush();
		        outputStream.close();
		    } catch (IOException e) {
		    	e.printStackTrace();
		    }
		}

}
